package com.wawayaya.service;


import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;
import com.android.volley.toolbox.JsonObjectRequest;
import com.wawayaya.util.TLog;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 进度条 生成包括 ：下载+解压 + 序列化每一个zip包的ser 文件
 */
public class DownloadTask extends AsyncTask<String, Integer, String> {

    private final static String TAG = DownloadTask.class.getSimpleName();

    private final static String PARSE_FILENAME_BOOKJSON = "book.json";
    private final static String PARSE_JASONPAGES = "pages";
    private final static String PARSE_JASONNAME = "name";
    private final static String PARSE_JASONTYPE = "type";
    private final static String PARSE_JASONINDEX = "index";
    private final static String PARSE_JASONPARTNO = "partno";
    private final static String PARSE_PAGEJASON = "page.json";
    private final static String PARSE_JASONDISPLAY = "display";
    private final static String PARSE_JASONIMG = "img";
    private final static String PARSE_JASONWG = "wg";
    private final static String PARSE_JASONFG = "fg";
    private final static String PARSE_JASONCN = "cn";
    private final static String PARSE_JASONCNPY = "cn_py";
    private final static String PARSE_JASONCNEN = "cn_en";
    private final static String PARSE_JASONCNPYEN = "cn_en_py";
    private final static String PARSE_JASONW = "w";
    private final static String PARSE_JASONH = "h";
    private final static String PARSE_JASONURI = "uri";
    private final static String PARSE_JASONREGION = "region";
    private final static String PARSE_JASONSENTENCE = "sentence";
    private final static String PARSE_JASONSSUBRECT = "sub_rect";
    private final static String PARSE_JASONSRECT = "rect";
    private final static String PARSE_JASONSLINES = "lines";
    private final static String PARSE_JASONSTEXT = "text";
    private final static String PARSE_JASONSCUTTEXT = "cut_text";
    private final static String PARSE_JASONSWORD = "wd";
    private final static String PARSE_JASONSPINYIN = "py";
    private final static String PARSE_JASONSVOICE = "voice";
    private final static String PARSE_JASONSMP3 = "mp3";
    private final static String PARSE_JASONSPOINTS = "points";
    private final static String PARSE_JASONSBEGIN = "bg";
    private final static String PARSE_JASONSEND = "ed";
    private final static String PARSE_JASONBG = "bg";
    private final static String PARSE_JASONPY = "py";
    private final static String PARSE_JASONEN = "en";
    private final static String PARSE_JASONLTX = "ltx";
    private final static String PARSE_JASONLTY = "lty";
    private final static String PARSE_JASONKOK = "kok";
    private final static String PARSE_JASONKOKCL = "kok_cl";
    private final static String PARSE_JASONTITLEMP3 = "title_mp3";
    private final static String PARSE_JASONTHUMB = "thumb";
    private final static String PARSE_JASONTRANS = "trans";
    private final static String PARSE_JASONSCREEN = "screen";

    private final static String PARSE_JASONSREAD = "sread";
    private final static String PARSE_JASONCENTERX = "center_x";
    private final static String PARSE_JASONCENTERY = "center_y";
    private final static String PARSE_JASONICONSIZE = "icon_size";

    private final static String PARSE_JASONBTYPE = "btype";


    private int m_iprogresscombinerange = 1;

    private Context m_ct = null;
    private int m_itype = 0;
    private int m_ibooknetid = 0;
    private int m_ibookorigid = 0;
    private int m_irowidx = 0;
    private int m_icolumnidx = 0;
    private JsonObjectRequest m_myRequestobj = null;
    private String m_sresult = null;

    private Object[] m_callbackobjs = null;

    private String m_spartdownloadurl = null;
    private String m_szipsavedpath = null;
    private int  m_iprogressend =0;


    private String m_spartstatuspath = null;

    private int    m_ipartnumber = 1;  // 'm_ipartnumber' starts from 1
    private String m_sunzipfolder;
    private String[] m_ssquizurls = null;
    private String m_ssersavedpath = null;
    private  int      zipCount= 0;
    private  int     download  = 0;
    private  int     serialize = 1;
    private  boolean  stopTask = false;
    private  int  bsId=0;
    public  DownloadTask(Context context){
        m_ct = context;
    }

    public void clear() {
        m_ibooknetid = 0;
        try{
            if(null != m_myRequestobj) {
                m_myRequestobj.cancel();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        m_myRequestobj = null;
    }

    @Override
    protected void onPostExecute(String result) {
        TLog.log(" DownloadTask : onPostExecute : " + m_itype + " " +
                ": this = : " + result + " m_iprogressend" + m_iprogressend);

    }

    @Override
    protected void onCancelled(String s) {
        TLog.log(" ----------DownloadTask : onCancelled savebookhasbeendownloadedprogress s:" + s);
        super.onCancelled(s);
    }

    @Override
    protected void onCancelled() {

    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);

    }

    // 'succ': is successful; null: is paused; 'error': error occurs
    @Override
    protected String doInBackground(String... sUrl) {
        TLog.log("DownloadTask : doInBackground 1111:  status not null  progress  " + isCancelled());
        int  saveProcess = 0;

      //  return handlebookimages(psd, m_iprogressend);
        return "";
    }


    private boolean initDownload(int  saveProcess) {
        boolean needunzip = false;
        InputStream input = null;
        RandomAccessFile raf = null;
        HttpURLConnection connection = null;
        try {
            TLog.log("DownloadTask :m_spartdownloadurl：  initDownload  " + m_spartdownloadurl + "   m_szipsavedpath: " + m_szipsavedpath);
            URL url = new URL(m_spartdownloadurl);
            File f = new File(m_szipsavedpath);
            connection = (HttpURLConnection) url.openConnection();
            connection.setAllowUserInteraction(true);
            connection.setConnectTimeout(5 * 1000);// 设置连接超时为5秒钟
            connection.setRequestMethod("GET");
            // connection.setRequestProperty("Range", "bytes=" + lsavedlength + "-");
            connection.connect();
            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            int responseCode = connection.getResponseCode();
            TLog.log("DownloadTask :responseCode：" + responseCode);
            if (responseCode != HttpURLConnection.HTTP_OK  && responseCode != HttpURLConnection.HTTP_PARTIAL)  {
                if(HttpURLConnection.HTTP_NOT_FOUND == responseCode){
                    try{
                      /*  String sfolder = m_bdd.getBookPath();
                        File fdel = new File(sfolder);
                        utils.clearDirorFile(fdel);*/
                       // fdel.delete();
                    }catch(Exception e){
                        e.printStackTrace();
                    }
                }
                return false;
            }
            if(connection.getResponseCode() == 416) {//Range越界，表示已经完成了
                if(isCancelled()) {
                    return false;
                }
            }
            else {

                if(isCancelled())  {
                    return false;
                }
                // this will be useful to display download percentage
                // might be -1: server did not report the length
                int fileLength = connection.getContentLength();
                // download the file
                input = connection.getInputStream();
                raf = new RandomAccessFile(f, "rw");
                raf.setLength(fileLength);
                byte data[] = new byte[4096];
                int count = 0;
                int total = count;
                while ((count = input.read(data)) != -1) {
                    if (isCancelled())  {
                        break;
                    }
                    if(stopTask){
                        cancel(true);
                         break;
                    }
                    total += count;
                    // publishing the progress....
                    if (fileLength > 0) {// only if total length is known
                        if(isCancelled()) {
                            return false;
                        }
                        float  process =  (float)total/(float)fileLength;
                        int  result = (int) (process * 100);
                        TLog.log("Download  HTTP_OK  = count  实际进度条  sjresult:" + result + " zipcount:" + zipCount);

                        float resultf = result/zipCount;
                        int g=(int)resultf;
                        TLog.log("Download  HTTP_OK  = count  实际进度条  g:" + g);

                        if(m_ipartnumber>1){
                            g = saveProcess+g;
                            TLog.log("Download ====== 大于1  HTTP_OK  = count  实际进度条  sjresult:  /4:" + g + " zipcount:" + zipCount + "  m_iprogressend:" + m_iprogressend);
                        }
                        mypublishProgress(g);
                    }
                    raf.write(data, 0, count);
                }
            }
            if(!isCancelled())  {
                //下载成功，开始解压
                needunzip = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (raf != null)
                    raf.close();
            } catch (IOException ignored) {
            }
            try {
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }
            try {
                if (connection != null)
                    connection.disconnect();
            }catch (Exception ignored) {
            }
        }
        return needunzip;
    }

    private boolean unzip() {
        String zipfilepath = m_szipsavedpath;
        String ziptodirectory = m_sunzipfolder;
        ZipInputStream in = null;
        FileOutputStream out = null;
        boolean bdone = false;
        try {
            File file = new File(ziptodirectory);
            file.mkdirs();
            InputStream zipFileName = new FileInputStream(zipfilepath);
            in = new ZipInputStream(new BufferedInputStream(zipFileName));
            ZipEntry entry = in.getNextEntry();
            while (null != entry && !isCancelled()) {
                if (isCancelled())  {
                    break;
                }
                String sname = entry.getName();
                if(TextUtils.isEmpty(sname)) {
                    continue;
                }
                sname = sname.replace("\\", "/");
                File entryFile = new File(ziptodirectory, sname);
                if(entry.isDirectory()){
                    // 创建以zip包文件名为目录名的根目录
                    entryFile.mkdirs();
                }
                else {
                    String sfilefolder = entryFile.getAbsolutePath();
                    int ipos = sfilefolder.lastIndexOf("/");
                    if(ipos > 0) {
                        sfilefolder = sfilefolder.substring(0, ipos);
                        new File(sfilefolder).mkdirs();
                    }
                    out = new FileOutputStream(entryFile);
                    byte [] buf = new byte[1024 * 10];
                    int len = 0;
                    while((len = in.read(buf, 0, 1024 * 10)) > 0){
                        if(isCancelled()) {
                            break;
                        }
                        out.write(buf,0,len);
                    }
                    out.close();
                    out = null;
                }
                in.closeEntry();
                entry = in.getNextEntry();
            }
            bdone = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if(null != out) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
        if(isCancelled()) {
            File f = new File(ziptodirectory);
          //  utils.clearDirorFile(f);
            f.delete();
        }
        return bdone & !isCancelled();
    }


    private void mypublishProgress(int iprogress){
        m_iprogressend = iprogress;

        publishProgress(iprogress);
    }


}
